<template>
  <div class="charteredDeploy">
    <el-form :inline="true" label-width="120px">
      <el-row>
        <el-form-item label="线路">
          <span>{{$parent.$parent.$parent.line.srcCity}}</span>
          <span>-</span>
          <span>{{$parent.$parent.$parent.line.dstCity}}</span>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="开始时间">
          <div>
            <el-select v-model="timeInfo.startIdx" placeholder="选择时间">
              <el-option v-for="(time, $index) in times" :key="$index" :label="time" :value="$index"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="结束时间">
          <div>
            <el-select v-model="timeInfo.endIdx" placeholder="选择时间">
              <el-option v-for="(time, $index) in times" :key="$index" :label="time" :value="$index"></el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="间隔时间">
          <el-input placeholder="请输入间隔时间" style="width: 217px;" v-model="timeInfo.intervalMin">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="预约时间">
          <el-input placeholder="请输入提前时间" style="width: 217px;" v-model="timeInfo.minReservMin">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-button type="primary" icon="plus" @click="add">添加</el-button>
      </el-row>
    </el-form>
    <el-table :data="lineList" stripe border style="width: 100%">
      <el-table-column align='center' prop="startIdx" label="开始时间">
        <template scope="props">
          <span>{{times[props.row.startIdx]}}</span>
        </template>
      </el-table-column>
      <el-table-column align='center' prop="times[endIdx]" label="结束时间">
        <template scope="props">
          <span>{{times[props.row.endIdx]}}</span>
        </template>
      </el-table-column>
      <el-table-column align='center' prop="intervalMin" label="间隔时间"></el-table-column>
      <el-table-column align='center' prop="minReservMin" label="预约时间"></el-table-column>
      <el-table-column align='center' prop="mileage" label="车型价格">
        <template scope="scope">
          <el-button @click="showCarTypePanel(scope.row)" size="small" type="primary">车型</el-button>
        </template>
      </el-table-column>
      <el-table-column align='center' label="操作">
        <template scope="scope">
          <el-button @click="showRevisePanel(scope.$index)" size="small" type="primary">修改</el-button>
          <el-button @click="del(scope.row.id, scope.row.lineId)" size="small" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="isReviseCD" title="修改拼车配置" size='tiny'>
      <el-form label-width="120px">
        <el-form-item label="开始时间">
          <div>
            <el-select v-model="modifyTime.startIdx" placeholder="选择时间">
              <el-option v-for="(time, $index) in times" :key="$index" :label="time" :value="$index"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="结束时间">
          <div>
            <el-select v-model="modifyTime.endIdx" placeholder="选择时间">
              <el-option v-for="(time, $index) in times" :key="$index" :label="time" :value="$index"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="间隔时间">
          <el-input placeholder="请输入间隔时间" style="width: 217px;" v-model="modifyTime.intervalMin">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="预约时间">
          <el-input placeholder="请输入提前时间" style="width: 217px;" v-model="modifyTime.minReservMin">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer ">
        <el-button @click="closeModifyPanel">取 消</el-button>
        <el-button type="primary " @click="modifyTimeInfo ">提 交</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="isReviseModelsPrice" title="修改车型价格" size='large'>
      <el-form :inline="true" label-width="120px">
        <el-row>
          <el-form-item label="线路">
            <span>{{$parent.$parent.$parent.line.srcCity}}</span>
            <span>-</span>
            <span>{{$parent.$parent.$parent.line.dstCity}}</span>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="开始时间">{{times[currentLine.startIdx]}}</el-form-item>
          <el-form-item label="结束时间">{{times[currentLine.endIdx]}}</el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="车型">
            <el-select v-model="carTypePriceInfo.carModelId" @change="carTypeChange" placeholder="请选择车型">
              <el-option v-for="(car, $index) in carTypes" :key="$index" :label="car.typeName" :value="car.carTypeId"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="包车起步价">
            <el-input v-model="carTypePriceInfo.price" style='width: 217px;'></el-input>
            <span>元</span>
          </el-form-item>
          <el-form-item label="包车包含公里数">
            <el-input v-model="carTypePriceInfo.mileage" style='width: 217px;'></el-input>
            <span>公里</span>
          </el-form-item>
          <el-button type="primary" icon="plus" @click="addCarTypePrice">添加</el-button>
        </el-row>
      </el-form>
      <el-table :data="carTypePriceList" stripe border style="width: 100%">
        <el-table-column align='center' label="车型">
          <template scope="scope">
            <span>{{carTypesObj[scope.row.carModelId]}}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' prop="price" label="包车起步价（元）"></el-table-column>
        <el-table-column align='center' prop="mileage" label="起步公里数"></el-table-column>
        <el-table-column width='400' align='center' prop="extraPrices" label="超里程价">
          <template scope="scope">
            <el-table :data="scope.row.extraPrices">
              <el-table-column align='center' label='适用公里数'>
                <template scope="extra">
                  <span>{{extra.row.mileageStart}} - {{extra.row.mileage}} 公里</span>
                </template>
              </el-table-column>
              <el-table-column align='center' prop="price" label='单价（元）'></el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column align='center' label="操作">
          <template scope="scope">
            <el-button @click="revise(scope.row)" size="small" type="primary">修改</el-button>
            <el-button @click="delTimeCarType(scope.row)" size="small" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog v-model="isReviseDC" title="修改默认拼车价" size='small'>
      <el-form :model="modifyCarPrice" label-width="100px" ref="cityPriceInfo">
        <el-form-item label="车型">
          <el-select v-model="modifyCarPrice.carModelId" placeholder="请选择车型">
            <el-option v-for="(car, $index) in carTypes" :key="$index" :label="car.typeName" :value="car.carTypeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起步价" prop="price">
          <el-input v-model="modifyCarPrice.price" auto-complete="off" style='width: 217px;'></el-input>
        </el-form-item>
        <el-form-item label="起步公里数" prop="mileage">
          <el-input v-model="modifyCarPrice.mileage" auto-complete="off" style='width: 217px;'></el-input>
        </el-form-item>
        <el-form-item label="超里程价" prop="extraPrices">
          <el-table :data="modifyCarPrice.extraPrices" stripe border style="width: 100%;">
            <el-table-column align='center' prop="price" label="适用公里数(公里)" width="240">
              <template scope="scope">
                <el-input :disabled="true" v-model="scope.row.mileageStart" class="price-input"></el-input>
                ——
                <el-input :disabled="(scope.$index + 1) < modifyCarPrice.extraPrices.length" v-model="scope.row.mileage" @blur='ruleMileageSize' class="price-input"></el-input>
              </template>
            </el-table-column>
            <el-table-column align='center' label="单价(元)">
              <template scope="scope">
                <el-input v-model="scope.row.price" class="price-input" @blur='rulePrice'></el-input>
              </template>
            </el-table-column>
            <el-table-column align='center' label="操作">
              <template scope="scope">
                <el-button v-if="(scope.$index + 1) == modifyCarPrice.extraPrices.length" @click="addExtraPrice(scope.row)" size="small" type="primary">添加</el-button>
                <el-button v-if="(scope.$index + 1) == modifyCarPrice.extraPrices.length && modifyCarPrice.extraPrices.length > 1" @click="delExtraPrice(scope.$index, scope.row)" size="small" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeCarTypePanel">取 消</el-button>
        <el-button type="primary" @click="updateDefaultPrice">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'lineCarpoolDeploy',
    data() {
      return {
        times: [], //可选时间列表
        value1: '',
        timeInfo: {
          startIdx: "",
          endIdx: "",
          intervalMin: "", //间隔分钟数
          minReservMin: "" //提前预约分钟数
        },
        line: {}, //线路详情
        lineList: [], //线路列表
        modifyTime: {}, //要修改的时间信息
        carTypes: [], //所有可用车型数据
        carTypesObj: {},
        currentLine: { //当前要设置车型配置的时间段
          startIdx: "",
          endIdx: ""
        },
        carTypePriceInfo: { //当前车型价格配置
          lineId: "",
          timeId: "",
          carModelId: "",
          price: "",
          mileage: ""
        },
        carTypePriceList: [],
        isReviseDC: false,
        isReviseCD: false, //时间修改层是否打开,true为打开,false为关闭
        isReviseModelsPrice: false, //车型价格设置层,true为打开,false为关闭
        modifyCarPrice: {},//需要修改的价格信息
        formLabelWidth: '120px'
      }
    },
    methods: {
      queryTimeList() {
        var that = this;
        this.$http.get("/queryLineTimeList.shtml", { params: { id: this.$parent.$parent.$parent.line.id || this.api.getUrlParams("lineId"), type: "charter" } })
          .then(data => {
            if(data.code == 200) {
              that.lineList = data.data;
            }
          });
      },
      //添加时间段
      add() {
        var that = this;
        this.line = this.$parent.$parent.$parent.line;
        if (this.timeInfo.startIdx === "") {
          this.$notify({
            title: '错误',
            message: "请选择开始时间",
            type: 'error'
          });
          return
        } else if (this.timeInfo.endIdx === "") {
          this.$notify({
            title: '错误',
            message: "请选择结束时间",
            type: 'error'
          });
          return
        } else if(this.timeInfo.intervalMin === ""  || this.timeInfo.intervalMin % 30 != 0 || this.timeInfo.intervalMin / 30 * 2 > (this.timeInfo.endIdx - this.timeInfo.startIdx)) {
          this.$notify({
            title: '错误',
            message: "间隔时间必须是30的整倍数，且 (结束时间 - 开始时间) * 30 要大于 间隔时间的2倍",
            type: 'error'
          });
          return;
        } else if(this.timeInfo.minReservMin === "" || this.timeInfo.minReservMin % 30 != 0) {
          this.$notify({
            title: '错误',
            message: "预约时间分钟数必须是30的倍数",
            type: 'error'
          });
          return;
        }
        this.$http.post("/lineTimeListAdd.shtml?type=charter", "param=" + JSON.stringify(this.timeInfo) + "&id=" + this.line.id)
          .then(data => {
            if(data.code == 200) {
              that.$notify({
                title: '成功',
                message: "添加成功",
                type: 'success'
              });
              that.queryTimeList();
              that.timeInfo = {
                startIdx: "",
                endIdx: "",
                intervalMin: "",
                minReservMin: JSON.parse(localStorage.getItem("lineItem")).minReservMin || 0
              }
            }
          })
      },
      //添加时间段车型价格
      addCarTypePrice() {
        if (this.tmpTypePriceState && this.tmpTypePrice.mileage == this.carTypePriceInfo.mileage && this.tmpTypePrice.price == this.carTypePriceInfo.price) {
          this.carTypePriceInfo.extraPrices = this.tmpTypePrice.extraPrices;
        }
        var param = "param=" + JSON.stringify(this.carTypePriceInfo),
          that = this;
        this.$http.post("/addCarTypePrice.shtml?type=charter", param)
          .then(data => {
            if(data.code == 200) {
              that.$notify({
                title: '成功',
                message: data.msg || "添加成功",
                type: 'success'
              });
              that.queryTimeCarTypeList();
              that.carTypePriceInfo.carModelId = ''
              that.carTypePriceInfo.price = ''
              that.carTypePriceInfo.mileage = ''
              if (that.carTypePriceInfo.hasOwnProperty("extraPrices")) {
                delete that.carTypePriceInfo.extraPrices
              }
            }
          });
      },
      //显示车型价格设置层
      showCarTypePanel(line) {
        this.isReviseModelsPrice = true;
        this.currentLine = line;
        this.carTypePriceInfo.lineId = line.lineId;
        this.carTypePriceInfo.timeId = line.id;
        if(!this.carTypes.length) {
          this.queryCarTypes();
        }
        this.queryTimeCarTypeList();
      },
      //显示时间修改层
      showRevisePanel(idx) {
        this.isReviseCD = true;
        this.modifyTime = this.lineList[idx];
      },
      //关闭时间修改层
      closeModifyPanel() {
        this.isReviseCD = false;
      },
      revise(carPrice) {
        this.isReviseDC = true;
        this.modifyCarPrice = carPrice;
      },
      //删除时间段
      del(timeId, lineId) {
        var params = {
          timeId: timeId,
          lineId: lineId
        };
        var that = this;
        params = "param=" + JSON.stringify(params);
        this.$http.post("/delLineTime.shtml?type=charter", params).then(data => {
          if(data.code == 200) {
            that.$notify({
              title: '成功',
              message: data.msg || "删除成功",
              type: 'success'
            });
            that.queryTimeList();
          }
        })
      },
      delTimeCarType(row) {
        var params = "param=" + JSON.stringify({lineId: this.currentLine.lineId, timeId: this.currentLine.id, priceId: row.id}),
          that = this;
        this.$http.post("/delTimeCarType.shtml?type=charter", params).then(data => {
          if(data.code == 200) {
            that.$notify({
              title: '成功',
              message: data.msg || "删除成功",
              type: 'success'
            });
            that.queryTimeCarTypeList();
          }
        })
      },
      //修改时间段信息
      modifyTimeInfo() {
        var params = "time=" + JSON.stringify(this.modifyTime),
          that = this;
        this.$http.post("/modifyTimeInfo.shtml?type=charter", params)
          .then(data => {
            if(data.code == 200) {
              that.$notify({
                title: '成功',
                message: data.msg || "修改成功",
                type: 'success'
              });
              that.queryTimeList();
              that.closeModifyPanel();
            }
          })
      },
      //获取车型数据
      queryCarTypes() {
        var that = this;
        this.$http.get("/allModelList.shtml").then(data => {
          if(data.code == 200) {
            that.carTypes = data.data;
            for (var i in data.data) {
              that.carTypesObj[data.data[i].carTypeId] = data.data[i].typeName;
            }
          } else {
            that.carTypes = [];
          }
        });
      },
      //获取当前时间段车型价格列表
      queryTimeCarTypeList() {
        var that = this;
        this.$http.get("/queryTimeCarTypeList.shtml?type=charter", {
          params: {
            lineId: this.carTypePriceInfo.lineId,
            timeId: this.carTypePriceInfo.timeId
          }
        }).then(data => {
          if(data.code == 200) {
            that.carTypePriceList = data.data
          }
        });
      },
      addExtraPrice(row) {
        var arry = this.modifyCarPrice.extraPrices;
        var mileage = arry[arry.length - 1].mileage;
        var mileageStart = arry[arry.length - 1].mileageStart;
        var price = arry[arry.length - 1].price;
        var re = /^[0-9]\d*$/;
        if(!mileage || ~~mileage <= ~~mileageStart || !(re.test(mileage))) {
          this.$notify({
            title: '错误',
            message: '结束公里数必须为正整数并且大于开始公里数！',
            type: 'error',
            duration: 3000
          });
        } else if(price <= 0 || !price) {
          this.$notify({
            title: '错误',
            message: '单价必须大于0！',
            type: 'error',
            duration: 3000
          });
        } else {
          this.modifyCarPrice.extraPrices.push({
            id: '',
            mileage: '',
            price: '',
            mileageStart: row.mileage
          })

        }
      },
      //修改车型价格
      updateDefaultPrice() {
        this.ruleMileageSize();
        this.rulePrice();
        var that = this;
        var lastIdx = this.modifyCarPrice.extraPrices.length - 1;
        if(parseFloat(this.modifyCarPrice.extraPrices[lastIdx].price) <= 0) {
          return;
        } else if(this.modifyCarPrice.extraPrices[lastIdx].mileage != "" && this.modifyCarPrice.extraPrices[lastIdx].mileage != 9999999) {
          that.$notify({
            title: '提示',
            message: '阶梯型定价中，最后一条适用里程数必须为空或者9999999.',
            type: 'error'
          });
          return
        }
        this.$http.post("/timeCarTypePriceUpdate.shtml?type=charter",
          "param=" + JSON.stringify(this.modifyCarPrice) + "&lineId=" + this.currentLine.lineId + "&timeId=" + this.currentLine.id
        ).then(function(data) {
          if(data.code == 200) {
            that.queryTimeCarTypeList();
            that.isReviseDC = false;
            that.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success'
            });
          }
        });
      },
      //价格验证
      rulePrice() {
        var arry = this.modifyCarPrice.extraPrices;
        var price = arry[arry.length - 1].price;
        if(price <= 0 || price == "") {
          this.$notify({
            title: '错误',
            message: '单价必须大于0！',
            type: 'error',
            duration: 3000
          });
        }
      },
      //公里数值的验证
      ruleMileageSize() {
        var arry = this.modifyCarPrice.extraPrices;
        var mileage = arry[arry.length - 1].mileage;
        var mileageStart = arry[arry.length - 1].mileageStart;
        var re = /^[0-9]\d*$/;
        if(mileage && ~~mileage <= ~~mileageStart) {
          this.$notify({
            title: '错误',
            message: '结束公里数必须为正整数并且大于开始公里数！',
            type: 'error',
            duration: 3000
          });
        } else if(mileage && !(re.test(mileage))) {
          this.$notify({
            title: '错误',
            message: '结束公里数必须为正整数并且大于开始公里数！',
            type: 'error',
            duration: 3000
          });
        }
      },
      //删除额外里程价
      delExtraPrice(index, row) {
        var that = this;
        this.$confirm('确认删除该超里程价格配置信息?', '删除超里程价信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          that.modifyCarPrice.extraPrices.splice(index, 1);
          var price = that.modifyCarPrice.extraPrices[index];
          price.mileage = 9999999;
          that.$set(that.modifyCarPrice.extraPrices, index, price)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //关闭车型价格编辑层
      closeCarTypePanel() {
        this.isReviseDC = false;
      },
      items() {
        const start = "00:00";
        const end = "24:00";
        const step = "00:30";
        const result = [];
        const that = this;
        if(start && end && step) {
          let current = start;
          while(that.compareTime(current, end) <= 0) {
            result.push(current);
            current = that.nextTime(current, step);
          }
        }
        return result;
      },
      parseTime(time) {
        const values = ('' || time).split(':');
        if(values.length >= 2) {
          const hours = parseInt(values[0], 10);
          const minutes = parseInt(values[1], 10);
          return {
            hours,
            minutes
          };
        }
        return null;
      },
      compareTime(time1, time2) {
        const value1 = this.parseTime(time1);
        const value2 = this.parseTime(time2);
        const minutes1 = value1.minutes + value1.hours * 60;
        const minutes2 = value2.minutes + value2.hours * 60;
        if(minutes1 === minutes2) {
          return 0;
        }
        return minutes1 > minutes2 ? 1 : -1;
      },
      nextTime(time, step) {
        const that = this;
        const timeValue = this.parseTime(time);
        const stepValue = this.parseTime(step);
        const next = {
          hours: timeValue.hours,
          minutes: timeValue.minutes
        };
        next.minutes += stepValue.minutes;
        next.hours += stepValue.hours;
        next.hours += Math.floor(next.minutes / 60);
        next.minutes = next.minutes % 60;
        return that.formatTime(next);
      },
      formatTime(time) {
        return(time.hours < 10 ? '0' + time.hours : time.hours) + ':' + (time.minutes < 10 ? '0' + time.minutes : time.minutes);
      },
      carTypeChange(id) {
        if (id == "") {
          return;
        }
        var that = this;
        this.$http.get("./getCarTypePriceById.shtml", {
          params: {
            lineId: this.$parent.$parent.$parent.line.id,
            tripMode: "charter",
            carModeId: id
          }
        }).then(data => {
          if (data.code == 200 && data.data.length > 0) {
            that.tmpTypePriceState = true
            data = data.data[0]
            that.tmpTypePrice = data
            that.carTypePriceInfo.price = data.price
            that.carTypePriceInfo.mileage = data.mileage
          } else {
            tmpTypePriceState = false
          }
        })
      }
    },
    watch: {
      "$parent.$parent.$parent.lineDetail": function(name) {
        if(name == "charteredDeploy") {
          this.queryTimeList();
          this.timeInfo.minReservMin = JSON.parse(localStorage.getItem("lineItem")).minReservMin
          this.times = this.items();
        }
      }
    },
    created() {
      if(sessionStorage.getItem("tabIdx") == "charteredDeploy") {
        this.queryTimeList();
        this.times = this.items();
      }
    }
  }
</script>
<style>
  .lineCarpoolDeploy .cell {
    padding: 0 !important;
  }
</style>